package com.cysd.ewmxns.sdw_ui.fragment

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.baidu.ocr.sdk.OCR
import com.baidu.ocr.sdk.OnResultListener
import com.baidu.ocr.sdk.exception.OCRError
import com.baidu.ocr.sdk.model.AccessToken

import com.baidu.ocr.ui.camera.CameraActivity
import com.cszy.ewmxns.base.BaseVMFragment
import com.cszy.ewmxns.ext.launch
import com.cszy.ewmxns.ext.toast
import com.cysd.ewmxns.sdw_adapter.indexGridAdapter
import com.cysd.ewmxns.sdw_adapter.indexListAdapter

import com.cysd.ewmxns.sdw_ui.activity.Sdw_CreatQrCodeActivity
import com.cysd.ewmxns.sdw_ui.activity.Sdw_DetailActivity1
import com.cysd.ewmxns.sdw_ui.activity.Sdw_DetailActivity3
import com.cysd.ewmxns.sdw_ui.activity.Sdw_DetailActivity4
import com.cysd.ewmxns.sdw_ui.activity.Sdw_OcrResultActivity
import com.cysd.ewmxns.sdw_ui.activity.Sdw_QrcodeActivity
import com.cysd.ewmxns.sdw_ui.activity.Sdw_SelectChangjingActivity
import com.cysd.ewmxns.sdw_ui.activity.Sdw_TxmScanResultActivity
import com.cysd.ewmxns.sdw_ui.dialog.FunctionGuideDialog
import com.cysd.ewmxns.sdw_ui.dialog.PermissoTipDialog
import com.cysd.ewmxns.sdw_ui.dialog.Sdw_UserAgreementDialog
import com.cysd.ewmxns.sdw_ui.dialog.Sdw_UserRefusedPermissonDialog
import com.cysd.ewmxns.sdw_utils.FileUtil
import com.cysd.ewmxns.sdw_utils.SpUtils
import com.cysd.ewmxns.sdw_viewmodel.IndexViewModel
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.XXPermissions
import com.hlyj.http.ad.NewGroMoreFeedAdManager
import com.hlyj.http.base.tool.lib_hlyj_base.Constants
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseAppConstans
import com.hlyj.http.base.tool.lib_hlyj_base.utils.BaseModuleSpUtils
import com.hnyyac.ad.mds.IAdView
import com.hnyyac.ad.mds.IAdViewListener
import com.hnyyac.ad.mds.manager.AdManager
import com.hnyyac.ad.mds.manager.AdManager.AdLoadListener

import com.hnyyac.ad.mds.utils.BaseAdConstants
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanIntentResult
import com.journeyapps.barcodescanner.ScanOptions
import qrrspeeelild.rqrc0ode.andro0ild.databinding.FragmentBlankBinding


class Sdw_IndexFragment : BaseVMFragment<IndexViewModel, FragmentBlankBinding>(), IAdViewListener {
    private var adapter: indexGridAdapter? = null
    private var adapter_list: indexListAdapter? = null
    private var hasGotToken = false
    private var pernissonTopdialog: PermissoTipDialog? = null
    var app_process: String? = "0" //整个应用流程
    var type_proces: String? = null //功能入口类型
    var function_type: String? = null //功能类型
    private var newGromoreFeedAd: NewGroMoreFeedAdManager? = null

    // 通用识别返回
    private val generalBasicLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            launch(Sdw_OcrResultActivity::class.java)
        }
    }

    // 条形码识别返回
    private val barcodeLauncher = registerForActivityResult<ScanOptions, ScanIntentResult>(
        ScanContract()

    ) { result: ScanIntentResult ->
        showLoading("正在识别中，请稍后")
        if (result.contents == null) {
            Toast.makeText(requireActivity(), "已取消", Toast.LENGTH_LONG).show()
            dismissLoading()

        } else {
            var str = result.contents
            var bundle = Bundle()
            bundle.putString("scanResult", str)
            launch(bundle, Sdw_TxmScanResultActivity::class.java)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        // 请选择您的初始化方式
        app_process = SpUtils.getInstance().getString(BaseAppConstans.APP_PROCESS)
        if (app_process == "0") {  //黑名单界面
            mBinding.llNotblack.visibility = View.GONE
            mBinding.llBlack.visibility = View.VISIBLE
            mBinding.tvTxmDesc.text = "扫条形码查看商品信息"
        } else {//非黑界面
            mBinding.llNotblack.visibility = View.VISIBLE
            mBinding.llBlack.visibility = View.GONE
        }
        initAccessToken()
    }

    override fun initData() {
        //获取首页grid数据
        adapter = indexGridAdapter()
        mBinding.recyIndexGrid.layoutManager = GridLayoutManager(requireContext(), 2)
        mBinding.recyIndexGrid.adapter = adapter
        adapter?.submitList(mViewModel.getIndexGrid())

        //获取首页黑名单下List列表
        adapter_list = indexListAdapter()
        mBinding.recyIndexBlacklist.layoutManager = LinearLayoutManager(requireContext())
        mBinding.recyIndexBlacklist.adapter = adapter_list
        adapter_list?.submitList(mViewModel.getIndexList())
        //启动流程
        newGromoreFeedAd = NewGroMoreFeedAdManager(
            requireActivity(),
            BaseAdConstants.FEEDAD_Id,
            mBinding?.fragmentContainer,
            62
        )
        newGromoreFeedAd?.loadAd()
        when (app_process) {
            "0" -> ""
            "1" -> app_process_1()
            "2" -> app_process_2()
        }
    }

    fun app_process_1() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.e("qin", "首页流程1插屏加载失败")
                    if (!SpUtils.getInstance()
                            .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                    ) {
                        if (!isAdded) return
                        showFunctionGuideDialog(requireActivity())
                    }
                }
            })
    }

    fun app_process_2() {
        type_proces = "第一次进首页插屏"
        AdManager.loadChapin(
            requireActivity(),
            2,
            this,
            object : AdLoadListener {
                override fun onAdLoadFailed(ad: IAdView?) {
                    Log.i("qin", "首页流程2插屏加载失败")
                    if (!SpUtils.getInstance()
                            .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
                    ) {
                        showFunctionGuideDialog(requireActivity())
                    }

                }
            })
    }

    /**
     * 显示功能引导弹窗
     */
    private fun showFunctionGuideDialog(context: Context) {
        // 创建对话框实例
        val dialog = FunctionGuideDialog(context)
        dialog.setCancelable(false) // 设置对话框不可取消
        dialog.setOnGuideDialogListener(object : FunctionGuideDialog.onGuideDialogListener {
            override fun btnOnclick() {
                closeFunctionGuideDialog(true)
            }

            fun  closeFunctionGuideDialog(isNextClose: Boolean){
                dialog.dismiss() // 关闭对话框
                // 处理点击引导内容的回调
                type_proces = "功能弹窗"
                if (isNextClose) {
                    SpUtils.getInstance().putBoolean(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG, true)
                }
                AdManager.loadVideo(
                    requireActivity(),
                    4,
                    this@Sdw_IndexFragment,
                    object : AdManager.AdLoadListener {
                        override fun onAdLoadFailed(ad: IAdView?) {
                            showInterstitialWithAgree()
                        }
                    })
            }

            override fun btnOnclose() {
                closeFunctionGuideDialog(false)
            }
        })

        // 显示对话框
        dialog.show()

    }

    private fun showInterstitialWithAgree() {
        type_proces = "功能弹窗关闭广告"
        AdManager.loadChapin_nocache(requireActivity(), 9, this, object : AdLoadListener {
            override fun onAdLoadFailed(ad: IAdView?) {
                showAgreementtDialog()
            }
        })
    }

    /**
     * 显示隐私协议弹窗
     */
    private fun showAgreementtDialog() {
        if (SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {

            return
        }
        var dialog = Sdw_UserAgreementDialog(requireActivity())
        dialog!!.show()
        dialog!!.setPrivateId(
            "您好" + "(" + BaseModuleSpUtils.getInstance().getString(Constants.PRIVACYID) + ")"
        )
        dialog!!.setCancelable(false)
        dialog!!.setOnAgreementListener(object : Sdw_UserAgreementDialog.AgreementDialogListner {
            override fun onDialogListener(clickType: Boolean) {
                if (clickType) {
                    SpUtils.getInstance().putBoolean(BaseAppConstans.isAgreeMent, true)
                    if (!SpUtils.getInstance().getBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN)) {
                        type_proces = "特殊情况点击同意隐私的插屏"
                        AdManager.loadChapin_nocache(
                            requireActivity(),
                            10,
                            this@Sdw_IndexFragment,
                            object : AdLoadListener {
                                override fun onAdLoadFailed(ad: IAdView?) {


                                }
                            })
                    }

                } else { //拒绝隐私协议
                    activity?.finish()

                }
            }
        })
    }

    override fun initListener() {
        //ocr文字识别
        mBinding.llImageToText.setOnClickListener {
            function_type = "图片提取文字"
            if (XXPermissions.isGranted(requireActivity(), android.Manifest.permission.CAMERA)) {
                // 监听扫描结果
                openCamera()

            } else {
                request_Permission(
                    requireActivity(),
                    android.Manifest.permission.CAMERA,
                    "相机",
                    "需要获取您的相机权限用来扫描二维码"
                )
            }

        }

        //解析wifi密码
        mBinding.llDecipherWifi.setOnClickListener {
            var bundle = Bundle()
            bundle.putString("type", "wifi")
            launch(bundle, Sdw_QrcodeActivity::class.java)
        }

        //生成二维码
        mBinding.ivTextToCode.setOnClickListener {
            launch(Sdw_CreatQrCodeActivity::class.java)
        }
        //生成二维码网址生成
        mBinding.rlUrl.setOnClickListener {
            launch(Sdw_CreatQrCodeActivity::class.java)
        }
        //生成二维码文本生成
        mBinding.rlLxr.setOnClickListener {
            launch(Sdw_CreatQrCodeActivity::class.java)
        }

        mBinding.rlWifi.setOnClickListener {
            launch(Sdw_CreatQrCodeActivity::class.java)
        }

        //条形码查价
        mBinding.llQueryShopPrice.setOnClickListener {
            function_type = "条形码查价"
            if (XXPermissions.isGranted(requireActivity(), android.Manifest.permission.CAMERA)) {
                // 监听扫描结果
                startScannerForTxm()

            } else {
                request_Permission(
                    requireActivity(),
                    android.Manifest.permission.CAMERA,
                    "相机",
                    "需要获取您的相机权限用来扫描二维码"
                )
            }
        }
        //wifi二维码解析
        mBinding.llScanCode.setOnClickListener {
            function_type = "wifi二维码解析"
            if (XXPermissions.isGranted(requireActivity(), android.Manifest.permission.CAMERA)) {
                var bundle = Bundle()
                bundle.putString("type", "wifi")
                launch(bundle, Sdw_QrcodeActivity::class.java)

            } else {
                request_Permission(
                    requireActivity(),
                    android.Manifest.permission.CAMERA,
                    "相机",
                    "需要获取您的相机权限用来扫描二维码"
                )
            }

        }

        //黑名单下 列表点击监听
        adapter_list?.setOnItemClickListener { adapter, view, position ->
            when (position) {
                0, 1 -> {
                    val bundle = Bundle()
                    bundle.putString("type", position.toString())
                    launch(bundle, Sdw_DetailActivity1::class.java)
                }

                3 -> {
                    launch(Sdw_DetailActivity3::class.java)
                }

                2 -> {
                    launch(Sdw_DetailActivity4::class.java)
                }
            }
        }

        //非黑界面操作
        mBinding.rvNotblackMain.setOnClickListener {
            // 调用方法尝试同时展示两个插屏广告
            type_proces = "rvNotblackMain"
            showReward()
        }
        //非黑扫二维码
        mBinding.rvSaoma.setOnClickListener {
            type_proces = "非黑扫码"
            showReward()

        }
        //非黑生成二维码
        mBinding.rvCreatQrcode.setOnClickListener {
            type_proces = "非黑生成"
            showReward()
        }
        //非黑扫码支付
        mBinding.rvSaomaPay.setOnClickListener {
            type_proces = "非黑支付"
            showReward()
        }
        mBinding.tvLookmore.setOnClickListener {
            launch(Sdw_SelectChangjingActivity::class.java)
        }
        adapter?.setOnItemClickListener { adapter, view, position ->
            var bundle = Bundle()
            bundle.putString("type", "general")
            launch(bundle, Sdw_QrcodeActivity::class.java)
        }

    }

    /**
     * 展示激励
     */
    private fun showReward() {
        AdManager.loadVideo(requireActivity(), 10, this, object : AdLoadListener {
            override fun onAdLoadFailed(ad: IAdView?) {
                //跳转不同的activity
                goActivityWithProcess()
            }
        })
    }

    private var lastNavigationTime: Long = 0
    private val NAVIGATION_DELAY_THRESHOLD = 2000L // 2秒

    private fun goActivityWithProcess() {
        // 检查Fragment有效性
        if (!isAdded || isDetached || activity == null) {
            return
        }

        // 防止重复跳转
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastNavigationTime < NAVIGATION_DELAY_THRESHOLD) {
            return
        }
        lastNavigationTime = currentTime

        when (type_proces) {
            "rvNotblackMain" -> {
                launch(Sdw_SelectChangjingActivity::class.java)
            }

            "第一次进首页插屏" -> {
                handleFirstLaunchProcess()
            }

            "功能弹窗关闭广告" -> {
                if (app_process == "1") {
                    showAgreementtDialog()
                }

            }
            "功能弹窗" -> {
                if (app_process == "1") {
                    //延时五秒在弹出一个插屏
                    showInterstitialWithAgree()
                }
            }

            "非黑扫码", "非黑支付" -> {
                val bundle = Bundle().apply {
                    putString("type", "general")
                }
                launch(bundle, Sdw_QrcodeActivity::class.java)
            }

            "非黑生成" -> {
                launch(Sdw_CreatQrCodeActivity::class.java)
            }
        }

        type_proces = ""
    }

    private fun handleFirstLaunchProcess() {
        if (!SpUtils.getInstance()
                .getBooleanWithTimeoutCheck(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG)
        ) {
            showFunctionGuideDialog(requireActivity())
        } else if (!SpUtils.getInstance().getBoolean(BaseAppConstans.isAgreeMent)) {
            showAgreementtDialog()
        }
    }

    /**
     * 以license文件方式初始化
     */
    private fun initAccessToken() {
        OCR.getInstance(requireActivity())
            .initAccessToken(object : OnResultListener<AccessToken> {
                override fun onResult(accessToken: AccessToken) {
                    val token = accessToken.accessToken
                    hasGotToken = true
                    Log.e("qin", "获取token成功")
                }

                override fun onError(error: OCRError) {
                    error.printStackTrace()
                    Log.e("qin", "获取token失败")
                }
            }, requireActivity().applicationContext)
    }

    private fun openCamera() {
        if (!checkTokenStatus()) {
            return
        }
        // 2. 创建并启动Intent
        val intent = Intent(requireActivity(), CameraActivity::class.java).apply {
            putExtra(
                CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(requireActivity().applicationContext).absolutePath
            )
            putExtra(
                CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL
            )
        }

        generalBasicLauncher.launch(intent)
    }

    private fun checkTokenStatus(): Boolean {
        if (!hasGotToken) {
            Toast.makeText(requireActivity(), "token还未成功获取", Toast.LENGTH_LONG).show()
        }
        return hasGotToken
    }


    /**
     * 条形码识别启动
     */
    private fun startScannerForTxm() {
        val options = ScanOptions()
        options.setDesiredBarcodeFormats(ScanOptions.ONE_D_CODE_TYPES)
        options.setPrompt("扫描条形码")
        options.setCameraId(0) // 使用设备的特定摄像头
        options.setBeepEnabled(true)
        options.setBarcodeImageEnabled(true)
        options.setOrientationLocked(false)
        barcodeLauncher.launch(options)
    }

    fun request_Permission(
        context: Activity,
        req_permisson: String,
        permisson_name: String,
        content: String
    ) {
        // 检查是否已标记为"不再询问"
        if (!SpUtils.getInstance().getBoolean(permisson_name)) { // 没有获取该权限或者没有永久拒绝
            showPermissonTipsDialog(context, content)
        }
        XXPermissions.with(context)
            // 申请单个权限
            .permission(req_permisson)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (pernissonTopdialog != null) {
                        pernissonTopdialog!!.dismiss()
                    }
                    if (!allGranted) {

                        toast("获取 $permisson_name 权限成功")
                        return
                    }
                    SpUtils.getInstance().putBoolean(permisson_name, true)
                    toast("获取 $permisson_name 权限成功")
                    when (function_type) {
                        "二维码内容" -> {
                            var bundle = Bundle()
                            bundle.putString("type", "general")
                            launch(bundle, Sdw_QrcodeActivity::class.java)
                        }

                        "条形码查价" -> {
                            startScannerForTxm()
                        }

                        "图片提取文字" -> {
                            openCamera()
                        }

                        "wifi二维码解析" -> {
                            var bundle = Bundle()
                            bundle.putString("type", "wifi")
                            launch(bundle, Sdw_QrcodeActivity::class.java)
                        }

                    }


                }

                override fun onDenied(
                    permissions: MutableList<String>,
                    doNotAskAgain: Boolean
                ) {
                    if (doNotAskAgain) {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }
                        showDoNotAskAgainDialog(
                            requireActivity(),
                            req_permisson,
                            permisson_name
                        )
                    } else {
                        if (pernissonTopdialog != null) {
                            pernissonTopdialog!!.dismiss()
                        }

                    }
                }
            })
    }

    /**
     * 用户单次拒绝
     */
    fun showPermissonTipsDialog(context: Context, content: String) {
        pernissonTopdialog = PermissoTipDialog(context)
        pernissonTopdialog!!.setPermissionMessage(content)
        pernissonTopdialog!!.show()
        pernissonTopdialog!!.setCancelable(false)
    }

    /**
     * 用户多次拒绝
     */
    fun showDoNotAskAgainDialog(context: Context, permission: String, permissionName: String) {
        var dialog = Sdw_UserRefusedPermissonDialog(context, permission)
        dialog.setPermissionMessage("您未授予 $permissionName 权限，请去设置中开启")
        dialog.setCancelable(false)
        dialog.show()
    }

    override fun onTrigger(adView: IAdView) {

    }

    override fun onAdShow(adView: IAdView) {
        when (type_proces) {
            "功能返回插屏" -> {
                SpUtils.getInstance()
                    .putBoolean(BaseAppConstans.IS_SHOW_YINSI_CHAPIN, true)//已经弹过了功能返回的插屏
            }

            "功能弹窗" -> {
                SpUtils.getInstance().putBoolean(BaseAppConstans.IS_SHOW_FUNCTION_DIALOG, true)
            }

        }
    }

    override fun onAdClick(adView: IAdView) {

    }

    override fun onAdClose(adView: IAdView) {
        // 检查 Fragment 是否仍然有效
        goActivityWithProcess()
    }

    override fun onError(msg: String) {

    }

    override fun onLoadError(adView: IAdView) {
        goActivityWithProcess()
    }

    override fun onSuccess(adView: IAdView) {

    }

    override fun onLoad(adView: IAdView) {

    }

    override fun onSkipped() {

    }

    override fun onNoAd() {

    }

    override fun onTimeOut() {

    }
}